"""
认证中间件
"""
from functools import wraps
from flask import request, g
from app.utils.auth import verify_token
from app.utils.response import error_response
from app.models import User

def auth_required(f):
    """需要认证的装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return error_response('缺少认证token', 401)
        
        user_id = verify_token(token)
        if not user_id:
            return error_response('无效或过期的token', 401)
        
        # 将用户信息存储到g对象中
        user = User.query.get(user_id)
        if not user:
            return error_response('用户不存在', 404)
        
        g.current_user = user
        return f(*args, **kwargs)
    
    return decorated_function

